/**
 * 
 */
package sailing.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.LoanAccount;
import sailing.io.file.ExcelFiles;
import sailing.listener.DATA;
import sailing.listener.DataListener;
import sailing.listener.UI;
import sailing.managers.LoanAccountManager;
import sailing.ui.base.DateChooser;
import sailing.ui.base.ITabPanel;
import sailing.ui.base.TopTitlePanel;
import sailing.ui.model.LoanAccountTableModel;
import sailing.utils.PD;
import sailing.utils.STask;
import sailing.utils.Utils;
import cjlite.logger.Logger;
import cjlite.utils.RandomUtils;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * @author simon
 * 
 */
public class LoanAccountDetailPanel extends AbstractJPanel implements ITabPanel {
	
	private static Logger logger = Logger.thisClass();
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//
	JTabbedPane tabbedpane;
	//
	private static final Color titleBgColor = new Color(183, 219, 255);

	private JTable loanAccountTable, importTable;
	private LoanAccountTableModel loanAccountTableModel, importTableModel;
	String path = null;
	

	private JTextField textDateTimefield;
	private JTextField textSummaryfield;
	private JTextField textIncomefield;
	private JTextField textExpendfield;
	private JTextField textHandlerfield;
	
	private JPanel importTablePanel;

	private JTextField importTF;

	/**
	 * @param application
	 */
	public LoanAccountDetailPanel(SingleFrameApplication application) {
		super(application);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.AbstractJPanel#initialPanel()
	 */
	@Override
	protected void initialPanel() {
		this.setLayout(new BorderLayout());
		tabbedpane = new JTabbedPane(JTabbedPane.LEFT);
		tabbedpane.setBorder(new EmptyBorder(5, 5, 5, 5));
		tabbedpane.addTab("新建条目", this.getNewRecordPanel());
		tabbedpane.addTab("往来明细列表", this.getDetailPanel());
		tabbedpane.addTab("Excel数据导入", this.getImportExcelPanel());
		tabbedpane.addTab("Excel数据导出", this.getExportExcelPanel());
		this.add(tabbedpane, BorderLayout.CENTER);
	}

	@Override
	public String getTabName() {
		return "借款项目明细";
	}

	@Override
	public JPanel getContentPanel() {
		return this;
	}

	private JPanel getNewRecordPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
		panel.setLayout(new BorderLayout(2, 2));
		panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		JPanel panelC = new JPanel();
		panelC.setLayout(new FlowLayout());
		panel.add(panelC, BorderLayout.CENTER);
		JPanel newRecordP = new JPanel();
		newRecordP.setBorder(new EmptyBorder(15,15,15,15));
		newRecordP.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(15, 15, 15, 15);
		c.weighty = 1.0;
		c.weightx = 1.0;
		
		
	    DateChooser dateChooser1 = DateChooser.getInstance("yyyy-MM-dd");
	    textDateTimefield = new JTextField("单击选择日期");
	    dateChooser1.register(textDateTimefield);
		JLabel labelTime = new JLabel("日期:"); 
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(labelTime, c);
		c.gridx = 1;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(textDateTimefield, c);
		
		JLabel labelCategory = new JLabel("内容:"); 
		textSummaryfield = new JTextField(5);
		c.gridx = 2;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(labelCategory, c);
		c.gridx = 3;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(textSummaryfield, c);
		
		///////////////////////////////////////////////////////////////////////////////
		JLabel labelSummary = new JLabel("收款:"); 
		textIncomefield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(labelSummary, c);
		c.gridx = 1;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(textIncomefield, c);
		
		JLabel labelOppositeAccounts = new JLabel("支出:"); 
		textExpendfield = new JTextField(10);
		c.gridx = 2;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(labelOppositeAccounts, c);
		c.gridx = 3;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(textExpendfield, c);
		
		/////////////////////////////////////////////////////////////////////////////
		JLabel labelGirobackNumber = new JLabel("经手人:"); 
		textHandlerfield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(labelGirobackNumber, c);
		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(textHandlerfield, c);
		
		JButton new_btn, cancel_btn;
		c.gridx = 1;
		c.gridy = 3;
		c.gridwidth = 1;
		new_btn = new JButton("确认");
		newRecordP.add(new_btn, c);
		c.gridx = 3;
		c.gridy = 3;
		c.gridwidth = 1;
		cancel_btn = new JButton("取消");
		newRecordP.add(cancel_btn, c);
		new_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				performOKAction();
			}
		});
		cancel_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				performCancelAction();
			}
		});
		panelC.add(newRecordP, BorderLayout.CENTER);

		return panel;
	}
	
	protected void performOKAction() {
		
		String dateTimeStr;
		String summaryStr;
		String incomeStr;
		String expendStr;
		String handlerStr;
		
		dateTimeStr = textDateTimefield.getText();
		Date dateTime = Utils.dateParse(dateTimeStr);
		summaryStr = textSummaryfield.getText();
		incomeStr = textIncomefield.getText();
		expendStr = textExpendfield.getText();
		handlerStr = textHandlerfield.getText();
		
		if (handlerStr.trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "请输经手人。", "提示！", JOptionPane.WARNING_MESSAGE);
			return;
		}
		
		LoanAccountManager rm = this.getApplication().getContext().getIoc().getInstance(LoanAccountManager.class);
		
		LoanAccount r;
		r = new LoanAccount();
		r.setId(RandomUtils.randomString16());
		r.setCreateTime(System.currentTimeMillis());
		r.setIncomeAmount(Double.parseDouble(incomeStr));
		r.setExpendAmount(Double.parseDouble(expendStr));
		r.setSummary(summaryStr);
		r.setHandler(handlerStr);
		r.setDateTime(dateTime.getTime());
		String msg = rm.save(r);
		
		if (msg == null || msg.length() == 0) {
			JOptionPane.showMessageDialog(this, "添加成功！");
			this.setVisible(false);
			UI.refresh();
		} else {
			JOptionPane.showMessageDialog(this, msg, "提示！", JOptionPane.WARNING_MESSAGE);
		}
	
		
	}
	
	protected void performCancelAction() {
		this.setVisible(false);
	}
	
	private JPanel getDetailPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(10, 10));
		panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);

		loanAccountTable = new JTable();
		loanAccountTableModel = new LoanAccountTableModel(this.getApplication());
		loanAccountTable.setModel(loanAccountTableModel);
		loanAccountTable.setRowHeight(35);
		loanAccountTable.setIntercellSpacing(new Dimension(15, 5));
		loanAccountTableModel.updateModel();
		JScrollPane scrollpane = new JScrollPane(loanAccountTable);
		panel.add(scrollpane, BorderLayout.CENTER);

		DATA.addDataListener(new DataListener(){

			@Override
			public void dataChanged() {
				loanAccountTableModel.fireTableDataChanged();	
			}});
		
		return panel;
	}
	
	private JPanel getImportExcelPanel() {
		
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(2, 2));
		// panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		panel.add(new TopTitlePanel("借款项目明细 - Excel数据导入"), BorderLayout.NORTH);

		JPanel panelC = new JPanel();
		panelC.setLayout(new BorderLayout());
		panelC.setBackground(new Color(255, 255, 255));

		panelC.add(this.getImportFilePanel(), BorderLayout.NORTH);
		// importTablePanel = new FormDebugPanel(true, true);
		importTablePanel = new JPanel();
		panelC.add(this.getImportTablePanel(importTablePanel, false, null), BorderLayout.CENTER);

		panel.add(panelC, BorderLayout.CENTER);
		return panel;
	}
	
	private Component getImportTablePanel(JPanel panel, boolean hasImport, List<LoanAccount> cvList) {
		panel.removeAll();

		FormLayout layout = new FormLayout("3dlu,280dlu:G,5dlu,90dlu,3dlu", "2dlu,f:100dlu:g,3dlu,20dlu");
		panel.setLayout(layout);

		if (!hasImport) {
			panel.doLayout();
			return panel;
		}
		// JPanel panel = new FormDebugPanel(true, true);
		// JPanel panel = new JPanel();

		CellConstraints cc = new CellConstraints();

		this.importTableModel = new LoanAccountTableModel(this.getApplication());

		this.importTable = new JTable();
		importTable.setModel(importTableModel);
		this.importTableModel.updateModel(cvList);
		// panel.add(new JLabel("no data"));

		JScrollPane scrollPane = new JScrollPane(importTable);
		scrollPane.setBackground(this.getBackground());
		panel.add(scrollPane, cc.xywh(2, 2, 3, 1));

		JButton importDatabtn;
		importDatabtn = new JButton("导入所有数据到数据库中");
		importDatabtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
		importDatabtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				performImportDataToDB();
			}
		});
		panel.add(importDatabtn, cc.xy(4, 4));
		panel.doLayout();
		return panel;
	}

	protected void performImportDataToDB() {
		PD.execute(this, new STask() {

			@Override
			public void run() {
				this.setMsg("开始保存.....");
				LoanAccountManager cm = getApplication().getContext().getIoc().getInstance(LoanAccountManager.class);

				if (cm.saveList(importTableModel.getDataList())) {

				}

				this.setMsg("保存到数据库完成.....");
				this.afterMsg("保存到数据库完成.....");
			}

		});

	}

	private Component getImportFilePanel() {

		// JPanel importFilePanel = new FormDebugPanel(true, true);
		JPanel importFilePanel = new JPanel();
		importFilePanel.setBorder(new EmptyBorder(10, 15, 6, 15));

		FormLayout layout = new FormLayout("10dlu,f:250dlu:g,5dlu,72dlu,10dlu", "1dlu,f:18dlu,1dlu");
		importFilePanel.setLayout(layout);

		CellConstraints cc = new CellConstraints();

		importTF = new JTextField(30);
		importTF.setEditable(false);
		importFilePanel.add(importTF, cc.xy(2, 2));

		JButton new_btn;
		new_btn = new JButton("选择要导入的Excel");
		new_btn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
		importFilePanel.add(new_btn, cc.xy(4, 2));
		new_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String filePath = ExcelFiles.getImportFile(LoanAccountDetailPanel.this);
				parseExcelFile(filePath);
			}
		});

		return importFilePanel;
	}

	protected void parseExcelFile(String path) {
		if (path != null) {
			this.importTF.setText(path);
			List<LoanAccount> cvList = ExcelFiles.loadData("导入 现金日记账", this, path, LoanAccount.class);
			this.getImportTablePanel(importTablePanel, true, cvList);

		} else {
			logger.trace("file path='{0}'", path);
		}
	}
	
	private JPanel getExportExcelPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(10, 10));
		panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);

		loanAccountTable = new JTable();
		JScrollPane scrollpane = new JScrollPane(loanAccountTable);
		// scrollpane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		// Set the frame characteristics
		setSize( 300, 200 );
		// Create columns names
		String columnNames[] = { "Column 1", "Column 2", "Column 3" };

		// Create some data
		String dataValues[][] =
		{
			{ "12", "234", "67" },
			{ "-123", "43", "853" },
			{ "93", "89.2", "109" },
			{ "279", "9033", "3092" }
		};

		// Create a new table instance
		loanAccountTable = new JTable( dataValues, columnNames );

		// Add the table to a scrolling pane
		scrollpane = new JScrollPane( loanAccountTable );
		
		panel.add(scrollpane, BorderLayout.CENTER);

		return panel;
	}
	private JPanel getCustomerMgtTopPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEtchedBorder());
		panel.setBackground(titleBgColor);
		panel.setOpaque(true);
		panel.add(new JLabel("项目回款明细"));
		return panel;
	}

	@Override
	public Icon getTabIcon() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getTabTip() {
		// TODO Auto-generated method stub
		return null;
	}

}
